/**
 *
 * @description:
 * @author: junyong.hong
 * @createTime: 2018/5/8
 * @version: 1.0.0.0
 * @history:
 *    1、
 *    2、
 *
 */
const Router = require('koa-router')

// 对前缀为api的进行处理
const apiRouter = new Router({ prefix: '/api' })

/**
 * 登录验证
 * @param ctx
 * @param next
 * @returns {Promise.<void>}
 */
const validateUser = async (ctx, next) => {
  if (!ctx.session.user) {
    ctx.status = 401
    ctx.body = 'need login'
  } else {
    await next()
  }
}

// 对所有的请求调用登录验证
apiRouter.use(validateUser)

const successResponse = (data) => {
  return {
    success: true,
    data
  }
}

apiRouter.
  // 获取列表数据
  get('/todos', async (ctx) => {
    const todos = await ctx.db.getAllTodos()
    ctx.body = successResponse(todos)
  })
  // 添加todo
  .post('/todo',  async (ctx) => {
    const data = await ctx.db.addTodo(ctx.request.body)
    ctx.body = successResponse(data)
  })
  // 修改todo
  .put('/todo/:id', async (ctx) => {
    const data = await ctx.db.updateTodo(ctx.params.id, ctx.request.body)
    ctx.body = successResponse(data)
  })
  // 删除todo
  .delete('/todo/:id', async (ctx) => {
    const data = await ctx.db.deleteTodo(ctx.params.id)
    ctx.body = successResponse(data)
  })
  // 批量删除todo
  .post('/delete/completed', async (ctx) => {
    const data = await ctx.db.deleteCompleted(ctx.request.body.ids)
    ctx.body = successResponse(data)
  })


module.exports = apiRouter
